<template>
  <div class="m-container">
    <Header></Header>
    <div class="mblog">
      <h2>{{ blog.title }}</h2>
      <el-link icon="el-icon-delete" style="float: right" type="danger" @click="deleteOne(blog.id)" v-if="showOrNot">
        删除
      </el-link>
      <el-link icon="el-icon-edit" v-if="ownBlog">
        <router-link :to="{name: 'BlogEdit', params: {blogId: blog.id}}">编辑</router-link>
      </el-link>
      <el-divider></el-divider>
      <div class="content markdown-body" v-html="blog.content"></div>
    </div>
  </div>
</template>
<script>
import 'github-markdown-css/github-markdown.css' // 然后添加样式markdown-body
import Header from "@/components/Header";

export default {
  name: "BlogDetail",
  components: {
    Header
  },
  data() {
    return {
      showOrNot: false,
      blog: {
        userId: null,
        title: "",
        description: "",
        content: ""
      },
      ownBlog: false
    }
  },
  methods: {
    getBlog() {
      const blogId = this.$route.params.blogId
      const _this = this
      this.$axios.get('/blog/' + blogId).then((res) => {
        _this.blog = res.data.data
        var MarkdownIt = require('markdown-it'),
            md = new MarkdownIt();
        var result = md.render(_this.blog.content);
        _this.blog.content = result
        // 判断是否是自己的文章，能否编辑
        _this.ownBlog = (_this.blog.userId === _this.$store.getters.getUser.id)
      });
    },
    deleteOne(id) {
      const _this = this
      this.$confirm('是否要删除' + _this.blog.title + '?', '删除数据', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
            this.$axios.delete('/blog/' + id, {
              headers: {
                "Authorization": localStorage.getItem("token")
              }
            }).then(res => {
              console.log(res)
              _this.$alert('操作成功' + res.data.message, '提示', {
                confirmButtonText: '确定',
                callback: action => {
                  _this.$router.push("/blogs")
                }
              });
            }, () => {
              _this.$alert('未登录，请登录', '提示', {
                confirmButtonText: '确定'
              })
            });
          }
      )
    }
  },
  created() {
    this.showOrNot = /*localStorage.getItem("token") !== ""*/true
    this.getBlog()
  }
}
</script>

<style scoped>

.mblog {
  margin: auto;
  width: 60%;
}

</style>
